import json
import re
from os import makedirs
from os.path import exists

import requests
from bs4 import BeautifulSoup
from gevent import os

dirName = 'json'
filename = 'FreePhotosWallpaper.json'

if __name__ == '__main__':
    txt = dirName + '/' + filename
    exist_file = exists(txt)
    if not exists(dirName):
        makedirs(dirName)
    empty = []

    imgDirPath = "/Users/victor/Program/Afra55/inc/FreeDynamicWallpaper5/photos"
    i = 1
    imgList = os.listdir(imgDirPath)
    convert = lambda text: int(text) if text.isdigit() else text.lower()
    imgList.sort(key=lambda x: [convert(c) for c in re.split('([0-9]+)', x)])
    for file in imgList:
        if not file.startswith('.') and not file.startswith('small'):
            name = str(file)
            big_image_url = "https://starrapps.github.io/FreeDynamicWallpaper5/photos/" + name
            preview_image_url = "https://starrapps.github.io/FreeDynamicWallpaper5/photos/" \
                                'small_' + name
            theme = {
                'id': name[:-5],
                'name': name[:-5],
                'preview_image_url': preview_image_url,
                'big_image_url': big_image_url
            }
            empty.append(theme)
            i += 1

    next_page = ''
    with open(txt, 'w', encoding='utf-8') as f:
        data_dict = {
            'themes': empty,
            'next_page': next_page
        }
        json_data = json.dumps(data_dict, indent=4)
        f.write(json_data)
        print(json_data)
        f.close()
